package se.bl.validate;

import java.io.File;

import qj.util.FileUtil;
import qj.util.XmlUtil;
import qj.util.XmlUtil.Tag;
import qj.util.funct.P1;
import qj.util.funct.P2;
import qj.util.structure.StructureBuilder;

public class ValidateJsp {
	public static void main(String[] args) {
		FileUtil.eachFile(new File("d:/Quan/Projects/itsw/bl-web/web/src/main/webapp"), new P2<File,String>() {public void e(File file,String path) {
			if (file.isDirectory() || !file.getName().endsWith(".jsp")) {
				return;
			}
			System.out.println("========== Checking: " + path + "\\" + file.getName());
			validate(file);
		}});
		
		
	}

	private static void validate(File file) {
		String content = FileUtil.readFileToString(file);
		
		StructureBuilder sb = new StructureBuilder(content);
		
		XmlUtil.eachBeginTag("a", content, checkAttr("href"));
		XmlUtil.eachBeginTag("img", content, checkAttr("src"));
		XmlUtil.eachBeginTag("form", content, checkAttr("action"));
		XmlUtil.eachBeginTag("input", content, checkAttr("src"));
		XmlUtil.eachBeginTag("link", content, checkAttr("href"));

		XmlUtil.eachBeginTag("c:url", content, new P1<Tag>() {public void e(Tag tag) {
			String attr = tag.attrs.get("value");
			if (attr == null 
					) {
				return;
			}
			

			if (
					attr.contains("${ctx")
					) {
				System.out.println(attr + " :: " + tag.innerHtml);
			}
		}});
		
	}

	private static P1<Tag> checkAttr(final String attrName) {
		return new P1<Tag>() {public void e(Tag tag) {
			String attr = tag.attrs.get(attrName);
			if (attr == null 
					|| attr.startsWith("<%=")
					|| attr.startsWith("<c:")
					|| attr.startsWith("${")
					|| attr.startsWith("http")
					|| attr.startsWith("mailto")
					|| attr.startsWith("#")
					) {
				return;
			}
			
			if (
					!attr.startsWith("${ctx")
					) {
				System.out.println(attr + " :: " + tag.innerHtml);
			}
		}};
	}
}
